package com.youan.serve.common;

import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youan.pangu.base.bean.ElementTree;
import com.youan.pangu.security.bean.LoginInfor;
import com.youan.serve.dao.domain.*;
import com.youan.serve.service.IFunctionService;
import com.youan.serve.service.IRoleService;
import com.youan.serve.service.IUserRoleService;
import com.youan.serve.service.IUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: 辛晟昊
 * @time: 2020/3/8 15:10
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IFunctionService functionService;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        if (CollectionUtils.isEmpty(userList)) {
            throw new UsernameNotFoundException("用户名不存在");
        }else if (userList.size() > 1) {
            throw new UsernameNotFoundException("用户名存在多个用户");
        }

        User user = userList.get(0);
        LoginInfor loginInfor = new LoginInfor(user.getUserName(),user.getUserPassword(),true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
        List<UserRole> roleUserList = userRoleService.list(wrapper.eq("user_id",user.getUserId()));
        List<String> roleIdList = new ArrayList<String>();
        if(roleUserList.size()<=0) {
            loginInfor.setRouters(new ArrayList< ElementTree >());
        }else {
            for(int i=0; i<roleUserList.size(); i++) {
                roleIdList.add(roleUserList.get(i).getRoleId());
            }
            loginInfor.setRouters(functionService.getFunctionsElementTreeByUserRoles(roleIdList));
        }
        loginInfor.setUserId(user.getUserId());
        return loginInfor;
    }
}
